﻿namespace Blaze.Framework
{
#if !UNITY_EDITOR && UNITY_ANDROID
    using UnityEngine;
#else
    using System.IO;
    using UnityEngine;

#endif

    /// <summary>
    /// 提供StreamingAssets的资源访问常用方法。
    /// </summary>
    public static class StreamingAssets
    {
        /// <summary>
        /// 从StreamingAssets加载资源。
        /// </summary>
        /// <param name="path">相对于StreamingAssets目录的路径</param>
        /// <returns>加载成功后的资源字节数组，若资源不存在则返回null</returns>
        public static byte[] Load(string path)
        {
#if !UNITY_EDITOR && UNITY_ANDROID
            return AndroidAssetUtility.CallStatic<byte[]>("load", path);
#else
            var fullPath = string.Format("{0}/{1}", Application.streamingAssetsPath, path);
            if (File.Exists(fullPath))
                return File.ReadAllBytes(fullPath);
            return null;
#endif
        }

#if !UNITY_EDITOR && UNITY_ANDROID
    /// <summary>
    /// 获取Android原生资源辅助类。
    /// </summary>
        private static AndroidJavaClass AndroidAssetUtility
        {
            get
            {
                if (mAndroidAssetUtility == null)
                    mAndroidAssetUtility = new AndroidJavaClass("com.blaze.unityplugin.AssetUtility");
                return mAndroidAssetUtility;
            }
        }

        private static AndroidJavaClass mAndroidAssetUtility;
#endif

        /// <summary>
        /// 获取一个值，表示指定路径下的资源是否存在。
        /// </summary>
        /// <param name="path">相对于StreamingAssets目录的路径</param>
        public static bool Exists(string path)
        {
#if !UNITY_EDITOR && UNITY_ANDROID
            return AndroidAssetUtility.CallStatic<bool>("exists", path);
#else
            var fullPath = $"{Application.streamingAssetsPath}/{path}";
            return File.Exists(fullPath);
#endif
        }
    }
}